﻿using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using Evolution.Utilities;
using Evolution.Expression;

namespace Evolution.UI.WebParts
{
    [Serializable]
    public class ExpressionAssertion : BaseAssertion
    {
        #region Properties
        
        public override string Caption
        {
            get { return "Expression"; }
        }

        public string Expression { get; set; }

        #endregion

        #region Methods

        public override void CreateInterface(ControlCollectionBuilder builder, PageActionEditor editor, int index)
        {
            TextBox key = new TextBox();
            key.ID = "Expression" + index;
            key.CssClass = "UserInput";
            key.Style[HtmlTextWriterStyle.Width] = "175px";
            key.ToolTip = "Expression";

            builder.AddTextBoxAndBuilder(key, false);

            builder.AddErrorPlaceholder("Expression" + index);

            builder.AddStaticText("<br/><br/>is evaluated to <strong>true</strong>.");
        }

        public override string GetDescription()
        {
            return "Expression is evaluated to <strong>true</strong>";
        }

        public override void ApplyChanges(PageActionEditor editor, int index)
        {
            TextBox obj1 = editor.FindControl("Expression" + index) as TextBox;

            if (obj1.Text.Trim() == String.Empty)
                editor.RaiseError("Expression" + index, "Specify an expression.");

            this.Expression = obj1.Text;            
        }

        public override void SyncChanges(PageActionEditor editor, int index)
        {
            (editor.FindControl("Expression" + index) as TextBox).Text = this.Expression;
        }       

        public override bool Evaluate(Page page, PageActionWebPart part)
        {
            ExpressionInterpreter interp = PageActionWebPart.GetInterpreter(page, part);

            return interp.EvaluateCondition(this.Expression);
        }

        public override bool IsValidAssertion(PageActionWebPart part, out string errorMessage)
        {
            errorMessage = String.Empty;
            if (StringUtility.IsNullOrEmpty(this.Expression))
                errorMessage = "No expression specified.";

            return String.IsNullOrEmpty(errorMessage);
        }

        #endregion
    }
}
